#!/bin/bash

getVersion() {
  branchName=$1
  version=$(echo $branchName | sed 's/^origin\///' | tr '_' '-' | tr -c '[:alnum:]-.' '.')
  version=$(echo $version | sed 's/\(.*\)\.\(.*\)/\1\2/')
  matcher=$(echo $version | grep -oE '(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)')

  if [ -n "$matcher" ]; then
    versionCode=$(echo $version | awk -v matcher="$matcher" '{print substr($0, index($0, matcher), length(matcher))}')
    preRelease=$(echo $version | awk -v matcher="$matcher" '{print substr($0, index($0, matcher) + length(matcher))}' | tr '-' '.' | sed 's/^\.\(.*\)/\1/')
  else
    versionCode="1.0.0"
    preRelease=$version
  fi

  preRelease=$(echo $preRelease | sed 's/\([0-9]\+\)\([.]\)/\2/g')

  if [ -z "$preRelease" ];then
    version="v$versionCode"
  else
    version="v${versionCode}-${preRelease}"
  fi

  version=$(echo $version | sed 's/\.\{2,\}/\./g' | sed 's/-\{2,\}/-/g' | tr '[:upper:]' '[:lower:]' | tr '.' '-')

  echo "$version"
}

branchName=$(git symbolic-ref --short -q HEAD)
tag=$(getVersion "$branchName")
echo "$tag"

if [ -n "$1" ];then
  tag=$1
fi

echo "选定的版本号为: $tag"
read -p "是否继续执行, 按enter键将进行依赖安装..." confirm
if [[ $confirm != "" ]]; then
  exit 1
fi

echo -e "\033[32m 开始安装 apaas 依赖 \033[0m"

packages=(
  "@x-apaas/x-apaas-frontend-i18n"
  "@x-apaas/x-dcloud-bpm"
  "@x-apaas/x-dcloud-business-event"
  "@x-apaas/x-dcloud-business-object"
  "@x-apaas/x-dcloud-low-code-engine"
  "@x-apaas/x-dcloud-page-engine"
  "@x-apaas/x-dcloud-page-mobile"
  "@x-apaas/x-dcloud-page-web"
  "@x-apaas/x-lib-rule-engine"
)

# 逐个安装特定依赖项
for package in "${packages[@]}"; do
  npm install "${package}@$tag" || exit 1
done

# 单独处理 x-dcloud-ui 包
npm uninstall @x-ui/x-dcloud-ui
npm install --save --save-exact @x-ui/x-dcloud-ui || exit 1

# 确保缓存有效
npm config set cache-min 9999999

# 安装其他依赖项并使用缓存
npm install || exit 1

# 使用一行命令删除多个目录
rm -rf ./node_modules/@x-apaas/x-{dcloud-bpm,dcloud-business-event,dcloud-business-object,dcloud-low-code-engine,dcloud-page-engine,dcloud-page-mobile,dcloud-page-web,dcloud-questionnaire-form,lib-rule-engine}/node_modules ./node_modules/@x-ui/x-{dcloud-ui,guard}/node_modules

echo -e "\033[32m 依赖安装成功 \033[0m"
  